import React from 'react';
import { Input, Select, Row, Col, Form, message, Button } from 'antd';
import FormItem from '../../../../../../components/FormItem';
import { DATABASE_TYPE } from '../../../../../../utils/constant';
import services from '../../../../../../services/api';
import { debounce } from 'lodash';

function AddDataBase(props) {
  const { form, value, queryList, closeModal } = props;
  const { validateFields } = form;

  const handleTest = () => {
    validateFields(async (err, values) => {
      if (!err) {
        const { code, data, msg } = await services.database.test(values);
        if (!code) {
          data ? message.success('连接成功') : message.error('连接失败');
        } else {
          message.error(msg);
        }
      }
    });
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    validateFields(async (err, values) => {
      if (!err) {
        const { code, msg } = value.id
          ? await services.database.update({ ...values, id: value.id })
          : await services.database.add(values);
        if (!code) {
          message.success(msg);
          queryList();
          closeModal();
        } else {
          message.error(msg);
        }
      }
    });
  };

  const getFormItems = () => {
    const { databaseName, databaseType = 'mysql', ipPort, userName, password, remark } = value || {};
    const layout = {
      labelCol: {
        span: 6,
      },
      wrapperCol: {
        span: 18,
      },
    };
    return [
      {
        label: {
          label: '数据库名称',
          ...layout,
        },
        name: 'databaseName',
        options: {
          initialValue: databaseName,
          rules: [
            { required: true, message: '请输入数据库名称', },
            { max: 128, message: '最长128个字符' },
            { pattern: /^[\u4E00-\u9FA5_a-zA-Z0-9]+$/, message: '限中英文数字下划线' }
          ],
        },
        component: <Input placeholder='请输入数据库名称' />,
      },
      {
        label: {
          label: '类型',
          ...layout,
        },
        name: 'databaseType',
        options: {
          initialValue: databaseType,
          rules: [
            {
              required: true,
              message: '请选择数据库类型',
            },
          ],
        },
        component: (
          <Select placeholder='请选择数据库类型' style={{ width: '100%' }}>
            {DATABASE_TYPE.map((item) => (
              <Select.Option value={item} key={item}>
                {item}
              </Select.Option>
            ))}
          </Select>
        ),
      },
      {
        label: {
          label: '数据库地址',
          ...layout,
        },
        name: 'ipPort',
        options: {
          initialValue: ipPort,
          rules: [
            {
              required: true,
              message: '请输入数据库地址',
            },
          ],
        },
        component: <Input placeholder='数据库地址' />,
      },
      {
        label: {
          label: '用户名',
          ...layout,
        },
        name: 'userName',
        options: {
          initialValue: userName,
          rules: [
            { required: true, message: '请输入用户名', },
            { max: 128, message: '最长128个字符' },
            { pattern: /^[\u4E00-\u9FA5_a-zA-Z0-9]+$/, message: '限中英文数字下划线' }
          ],
        },
        component: <Input placeholder='用户名' />,
      },
      {
        label: {
          label: '密码',
          ...layout,
        },
        name: 'password',
        options: {
          initialValue: password,
          rules: [
            {
              required: true,
              message: '请输入密码',
            },
          ],
        },
        component: <Input.Password placeholder='密码' />,
      },
      {
        label: {
          label: '备注',
          ...layout,
        },
        name: 'remark',
        options: {
          initialValue: remark,
        },
        component: <Input.TextArea placeholder='不超过256个字符' maxLength={256} />,
      },
    ].filter(Boolean);
  };

  return (
    <Form onSubmit={() => false}>
      <Row type='flex'>
        {getFormItems().map((item) => {
          return (
            <Col span={24} key={item.name}>
              <FormItem form={form} item={item} colNum={1} />
            </Col>
          );
        })}
      </Row>
      <div style={{ marginTop: '20px', textAlign: 'center' }}>
        <Button className='marr10' onClick={debounce(handleTest, 500)}>
          连通测试
        </Button>
        <Button className='marr10' onClick={() => closeModal()}>
          取消
        </Button>
        <Button type='primary' onClick={handleSubmit}>
          确定
        </Button>
      </div>
    </Form>
  );
}
export default Form.create()(AddDataBase);
